const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const { escapeRegex } = require('@/utils');

// 运动建议模型
const sportAdviceSchema = new Schema({
  user_id: { 
    type: Schema.Types.ObjectId, 
    ref: 'User',
    required: true 
  },
  plan_id: { 
    type: Schema.Types.ObjectId, 
    ref: 'TrainingPlan' 
  },
  content: String,
  generate_time: { type: Date, default: Date.now },
  is_read: { type: String, default: 0 }
});

sportAdviceSchema.statics.getSportAdvices = async function (user_id, plan_id, is_read, user_name, offset = 0, limit = 10) {
  try {
    const query = {};    
    // 添加用户ID查询条件
    if (user_id) {
      query.user_id = user_id;
    }
    // 添加训练计划ID查询条件
    if (plan_id) {
      query.plan_id = plan_id;
    }
    // 添加已读/未读查询条件
    if (is_read) {
      query.is_read = is_read;
    }
    // 根据用户名查询
    if (user_name) {
      const { User } = require('../user');
      const parentQuery = {};
      const escapedUserName = escapeRegex(user_name);
      parentQuery.name = { $regex: escapedUserName, $options: 'i' };
      const users = await User.find(parentQuery).lean();
      if (users.length === 0) return { total: 0, rows: [] };
      query.user_id = { $in: users.map(user => user._id) };
    }
    // 先统计符合条件的记录总数
    const total = await this.countDocuments(query);
    // 再进行分页查询和关联数据获取
    const rows = await this.aggregate([
      { $match: query },
      { $lookup: {
        from: 'users',
        localField: 'user_id',
        foreignField: '_id',
        as: 'user_info'
      }},
      { $lookup: {
        from: 'trainingplans',
        localField: 'plan_id',
        foreignField: '_id',
        as: 'plan_info'
      }},
      { $unwind: {
        path: '$user_info',
        preserveNullAndEmptyArrays: true
      }},
      { $unwind: {
        path: '$plan_info',
        preserveNullAndEmptyArrays: true
      }},
      { $project: {
        _id: 1,
        user_id: 1,
        plan_id: 1,
        content: 1,
        generate_time: 1,
        is_read: 1,
        user_name: '$user_info.name',
        plan_name: '$plan_info.name'
      }},
      { $skip: Number(offset) },
      { $limit: Number(limit) },
      { $sort: { generate_time: -1 } }
    ]);
    return { rows, total };
  } catch (error) {
    console.error('获取运动建议失败:', error);
    throw new Error('获取运动建议失败');
  }
};

sportAdviceSchema.statics.createSportAdvices = async function (params) {
  try {
    const sportAdvice = new this(params);
    return await sportAdvice.save();
  } catch (error) {
    console.error('创建运动建议失败:', error);
    throw new Error('创建运动建议失败');
  }
};

sportAdviceSchema.statics.updateSportAdvices = async function (id, params) {
  try {
    const sportAdvice = await this.findByIdAndUpdate(id, params, { new: true });
    if (!sportAdvice) throw new Error('运动建议不存在');
    return sportAdvice;
  } catch (error) {
    console.error('标记运动建议为已读失败:', error);
    throw new Error('标记运动建议为已读失败');
  }
};


module.exports = mongoose.model('SportAdvice', sportAdviceSchema);